// api/auth.ts
import http from './http'
import { requestWithRetry } from '@/utils/retry'

// 认证API服务
export const authAPI = {
  // 用户登录
  async login(username: string, password: string) {
    try {
      // 使用重试机制进行登录
      const response = await requestWithRetry(
        () => http.post('/auth/login', { username, password }),
        3, // 最多重试3次
        1000 // 基础延迟1秒
      );
      
      return {
        success: true,
        data: response.data
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '登录失败'
      };
    }
  },

  // 用户登出
  async logout() {
    try {
      await http.post('/auth/logout');
      localStorage.removeItem('token');
      return {
        success: true,
        data: null,
        message: '登出成功'
      };
    } catch (error: any) {
      localStorage.removeItem('token');
      return {
        success: true,
        data: null,
        message: '登出成功'
      };
    }
  },

  // 获取当前用户信息
  async getCurrentUser() {
    try {
      // 使用重试机制获取当前用户信息
      const response = await requestWithRetry(
        () => http.get('/auth/current-user'),
        3, // 最多重试3次
        1000 // 基础延迟1秒
      );
      
      return {
        success: true,
        data: response.data
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '获取用户信息失败'
      };
    }
  },

  // 检查是否已登录
  isAuthenticated(): boolean {
    const token = localStorage.getItem('token');
    return !!token;
  }
}